package com.wuzao.aop.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

@RestController
public class MyApiController {

    private final RestTemplate restTemplate;

    public MyApiController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @PostMapping("/tts")
    public ResponseEntity<Map<String, Object>> handleRequest(@RequestBody Map<String, Object> requestData) {
        // 打印接收到的数据
        System.out.println("Received data: " + requestData);

        // 检查请求头中是否存在自定义标志，防止无限递归
        if (!"true".equals(requestData.get("X-Forwarded"))) {
            // 作为客户端将相同的请求发送到指定地址
            String url = "http://127.0.0.1:9966/tts";
            HttpHeaders headers = new HttpHeaders();
            headers.set("X-Forwarded", "true");

            ResponseEntity<Map> response = restTemplate.postForEntity(url, requestData, Map.class);

            // 打印客户端请求的响应
            System.out.println("Forwarded request response: " + response.getBody());

            // 返回最终的响应
            return ResponseEntity.ok(response.getBody());
        } else {
            // 直接返回接收到的数据，避免无限递归
            Map<String, Object> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "Data received and not forwarded");
            response.put("data", requestData);
            return ResponseEntity.ok(response);
        }
    }
}
